# -*- coding: utf-8 -*-
'''
	请求报文
'''
import uvicorn
from pydantic import BaseModel, Field
from fastapi import FastAPI, Query, Path, Form, Request
from typing import Optional

app = FastAPI()

# http://127.0.0.1/api/index?id=10
# http://127.0.0.1/api/index/1000
#获取query和path参数
@app.get("/test/{name}")
def test(
    x:int=Query(lt=1000), 
    y:int=Query(default=200),
    name:str=Path(min_length=5)
):
    return {"code":200,"msg":"x=%d, y=%d" % (x,y)}

class PostData(BaseModel):
    a:int = Field(default=100)
    b:Optional[int] = Field(default=200)

#接收request body数据（formData和json）
@app.post("/test2")
def test2(
    req: Request,
    data: PostData #json
    # a:int=Form(lt=1000),#formData
    # b:str=Form(pattern="^\d+$")#formData
):
    #获取header数据
    token = req.headers.get("token")
    return {}

#分页查询Demo
@app.get("/page")
def page(
    page:int=Query(default=1),
    limit:int=Query(default=10)
):
    data = [v for v in range(560)]

    start_pos = (page-1)*limit
    
    total = len(data)
    rows  = data[start_pos:start_pos+limit]
    return {
        "code":200, 
        "msg":"ok",
        "total":total,
        "rows":rows
    }

    return {
        "code":200, 
        "msg":"OK",
        "data":req.headers.get("token")
    }




if __name__ == '__main__':

    uvicorn.run(
        app     = 'example07-请求报文:app', 
        host    = "0.0.0.0", 
        port    = 8080, 
        reload  = True
    )